<?php
namespace app\index\model;
use think\Model;
use think\Db;

class Wechat extends Model{
	private $appId = 'wxdbb484fc33a0b2d1';
 	private $appSecret = '5ff865bb0b20cf0e6943cfe3af250e41';

	public function getSignPackage() {
		$jsapiTicket = $this->getJsApiTicket();
	
		// 注意 URL 一定要动态获取，不能 hardcode.
		$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
	
		$timestamp = time();
		$nonceStr = $this->createNonceStr();
	
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
	
		$signature = sha1($string);
	
		$signPackage = array(
		  "appId"     => $this->appId,
		  "nonceStr"  => $nonceStr,
		  "timestamp" => $timestamp,
		  "url"       => $url,
		  "signature" => $signature,
		  "rawString" => $string
		);
		return $signPackage; 
  }

  private function createNonceStr($length = 16) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for ($i = 0; $i < $length; $i++) {
		  $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);   
				//随机在一个位置取一个长度的字符串,因为从0开始所以要减1
		}
		return $str;
  }

   private function getJsApiTicket() {
		// jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
		
		$sql = "select * from yz_jsconfig where id=1";
		$row = Db::query($sql)[0];
		
		$old_time = strtotime($row['time']);
		$now_time = time();
		$now_date = date("Y-m-d H:i:s");
		$cha = $now_time-$old_time;
		
		if($cha>3600){
			$accessToken = $this->getAccessToken();

			$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
		 	$res = json_decode($this->httpGet($url));
		 	$ticket = $res->ticket;
			
			$sql = "update yz_jsconfig set  ticket='$ticket',time='$now_date' where id=1";
            Db::query($sql);
			
			$sql = "select * from yz_jsconfig where id=1";
			$row = Db::query($sql)[0];
		}else{
			$sql = "select * from yz_jsconfig where id=1";
			$row = Db::query($sql)[0];
		}
		
		
		$ticket = $row['ticket'];
		return $ticket;
  }

   function getAccessToken() {
		// access_token 应该全局存储与更新
		$sql = "select * from yz_access_token where id=1";
		$row = Db::query($sql)[0];
		
		$old_time = strtotime($row['time']);
		$now_time = time();
		$now_date = date("Y-m-d H:i:s");
		$cha = $now_time-$old_time;
		
		if($cha>3600){
			$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
			$res = json_decode($this->httpGet($url));
		  	$access_token = $res->access_token;
			$sql = "update yz_access_token set  access_token='$access_token',time='$now_date' where id=1";
            Db::query($sql);
			
			$sql = "select * from yz_access_token where id=1";
			$row = Db::query($sql)[0];
		}else{
			$sql = "select * from yz_access_token where id=1";
			$row = Db::query($sql)[0];
		}
		
		
		$access_token = $row['access_token'];
   		return $access_token;
  }

	
  function new_getAccessToken() {
		// access_token 应该全局存储与更新
		$sql = "select * from yz_access_token where id=1";
		$row = Db::query($sql)[0];
		
		$old_time = strtotime($row['time']);
		$now_time = time();
		$now_date = date("Y-m-d H:i:s");
		$cha = $now_time-$old_time;
		
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
		$res = json_decode($this->httpGet($url));
		$access_token = $res->access_token;
		$sql = "update yz_access_token set  access_token='$access_token',time='$now_date' where id=1";
        Db::query($sql);
		
		$sql = "select * from yz_access_token where id=1";
		$row = Db::query($sql)[0];
		
		$access_token = $row['access_token'];
   		return $access_token;
  }	



  /*获取个人信息*/
  public function getUserInfo($ACCESS_TOKEN,$OPENID){
		$Url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$ACCESS_TOKEN."&openid=".$OPENID."&lang=zh_CN";
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$Url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		return json_decode(curl_exec($ch));
  }	



  function httpGet($url) {
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 500);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($curl, CURLOPT_URL, $url);
	
		$res = curl_exec($curl);
		curl_close($curl);
	
		return $res;
  }
  
  
 
 

	
		
	 /*post服务器请求*/	
	  public function https_request($url,$data = null){                   // 模拟提交数据函数
		     $curl = curl_init();                                         // 启动一个CURL会话   
			 curl_setopt($curl,CURLOPT_URL,$url);                         // 要访问的地址
			 curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);                 // 对认证证书来源的检查 
			 curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0);                 // 从证书中检查SSL加密算法是否存在
			 if(!empty($data)){  
				  curl_setopt($curl,CURLOPT_POST,1);                      // 发送一个常规的Post请求
				  curl_setopt($curl,CURLOPT_POSTFIELDS,$data);            // Post提交的数据包x
			 }  
			 curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);                 // 获取的信息以文件流的形式返回
			 $output = curl_exec($curl);                                  // 执行操作
			 curl_close($curl);                                           // 关闭CURL会话
			 return $output;  								              // 返回数据										
	  } 
	  
 

}

?>